package it.softphone.cmc.server.rest;


import it.softphone.commons.json.server.JSONUtils;

import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;


@Produces( MediaType.APPLICATION_JSON )
@Provider
public class CMCExceptionProvider implements ExceptionMapper<Exception> {

	@Context HttpHeaders headers;
	
	@Override
	public Response toResponse( Exception exception) {

		ResponseBuilder rb ;
		
		if( exception instanceof CMCRestException ) {
			
			rb =  Response.status( ((CMCRestException)exception).getStatus() );
		}
		if( exception instanceof WebApplicationException ) {
			
			rb = Response.status(((WebApplicationException)exception).getResponse().getStatus());
		}
		else {
			rb = Response.status(Status.INTERNAL_SERVER_ERROR);
		}
		
		return rb.entity( JSONUtils.toJSON(exception)).build();
	}

}
